<template>
  <div class="content-list">
    <div class="page-header">
      <h2>内容管理</h2>
      <el-button type="primary" @click="addContent">添加内容</el-button>
    </div>
    
    <div class="filter-bar">
      <el-input
        v-model="searchQuery"
        placeholder="搜索内容标题"
        prefix-icon="Search"
        clearable
        @input="handleSearch"
        class="search-input"
      />
      
      <el-select v-model="statusFilter" placeholder="状态筛选" @change="handleFilter">
        <el-option label="全部" value="" />
        <el-option label="已发布" value="published" />
        <el-option label="草稿" value="draft" />
        <el-option label="弃用" value="disabled" />
      </el-select>
      
      <el-select v-model="templateFilter" placeholder="模板筛选" @change="handleFilter">
        <el-option label="全部" value="" />
        <el-option 
          v-for="template in templates" 
          :key="template.id" 
          :label="template.name" 
          :value="template.id" 
        />
      </el-select>
    </div>
    
    <el-table
      :data="filteredContents"
      style="width: 100%"
      border
      v-loading="loading"
    >
      <el-table-column prop="title" label="标题" min-width="200">
        <template #default="scope">
          <a @click.prevent="editContent(scope.row)" class="content-title-link">
            {{ scope.row.title }}
          </a>
        </template>
      </el-table-column>
      
      <el-table-column prop="template_name" label="类型/模板" width="150">
        <template #default="scope">
          <div class="template-info">
            <el-icon><Document /></el-icon>
            <span>{{ scope.row.template_name }}</span>
          </div>
        </template>
      </el-table-column>
      
      <el-table-column prop="status" label="状态" width="100">
        <template #default="scope">
          <el-tag :type="getStatusType(scope.row.status)">
            {{ getStatusText(scope.row.status) }}
          </el-tag>
        </template>
      </el-table-column>
      
      <el-table-column prop="created_at" label="创建时间" width="180" />
      <el-table-column prop="updated_at" label="更新时间" width="180" />
      
      <el-table-column label="操作" width="180" fixed="right">
        <template #default="scope">
          <el-button 
            size="small" 
            @click="previewContent(scope.row)"
            title="预览"
          >
            <el-icon><View /></el-icon>
          </el-button>
          <el-button 
            size="small" 
            type="primary" 
            @click="editContent(scope.row)"
            title="编辑"
          >
            <el-icon><Edit /></el-icon>
          </el-button>
          <el-button 
            size="small" 
            type="danger" 
            @click="deleteContent(scope.row)"
            title="删除"
          >
            <el-icon><Delete /></el-icon>
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <div class="pagination-container">
      <el-pagination
        background
        layout="prev, pager, next"
        :total="totalContents"
        :page-size="pageSize"
        :current-page="currentPage"
        @current-change="handlePageChange"
      />
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Document, View, Edit, Delete, Search } from '@element-plus/icons-vue'

interface ContentItem {
  id: number
  title: string
  template_id: number
  template_name: string
  status: 'published' | 'draft' | 'disabled'
  path: string
  created_at: string
  updated_at: string
  content: any
}

interface Template {
  id: number
  name: string
  description: string
}

const router = useRouter()
const contents = ref<ContentItem[]>([])
const templates = ref<Template[]>([])
const loading = ref(true)
const searchQuery = ref('')
const statusFilter = ref('')
const templateFilter = ref('')
const currentPage = ref(1)
const pageSize = ref(10)
const totalContents = ref(0)

// 获取内容列表
const fetchContents = async () => {
  loading.value = true
  try {
    // 模拟API调用，实际项目中应该调用真实API
    setTimeout(() => {
      // 从localStorage获取数据，如果没有则创建示例数据
      const storedContents = localStorage.getItem('contentItems')
      if (storedContents) {
        contents.value = JSON.parse(storedContents)
      } else {
        // 创建示例数据
        contents.value = [
          {
            id: 1,
            title: '美容院夏季护肤攻略',
            template_id: 1,
            template_name: '新闻文章',
            status: 'published',
            path: '/news/summer-skincare',
            created_at: '2023-07-15 10:30:00',
            updated_at: '2023-07-15 14:20:00',
            content: {
              summary: '夏季护肤的正确方式',
              content: '夏季皮肤容易出油，应该如何护理...',
              cover_image: ''
            }
          },
          {
            id: 2,
            title: '新品面膜上市',
            template_id: 2,
            template_name: '产品展示',
            status: 'draft',
            path: '/products/new-mask',
            created_at: '2023-07-20 09:15:00',
            updated_at: '2023-07-20 09:15:00',
            content: {
              product_name: '水光焕颜面膜',
              price: 128,
              description: '深层补水面膜...'
            }
          },
          {
            id: 3,
            title: '美甲服务介绍',
            template_id: 1,
            template_name: '新闻文章',
            status: 'disabled',
            path: '/services/nail-art',
            created_at: '2023-06-10 16:45:00',
            updated_at: '2023-07-01 11:30:00',
            content: {
              summary: '专业美甲服务详情',
              content: '我们提供多种美甲服务...',
              cover_image: ''
            }
          }
        ]
        localStorage.setItem('contentItems', JSON.stringify(contents.value))
      }
      
      totalContents.value = contents.value.length
      loading.value = false
    }, 500)
  } catch (error) {
    ElMessage.error('获取内容列表失败')
    console.error(error)
    loading.value = false
  }
}

// 获取模板列表
const fetchTemplates = async () => {
  try {
    // 模拟API调用，实际项目中应该调用真实API
    setTimeout(() => {
      // 从localStorage获取数据，如果没有则创建示例数据
      const storedTemplates = localStorage.getItem('contentTemplates')
      if (storedTemplates) {
        templates.value = JSON.parse(storedTemplates)
      } else {
        // 创建示例数据
        templates.value = [
          { id: 1, name: '新闻文章', description: '适用于发布新闻、博客等文章类内容' },
          { id: 2, name: '产品展示', description: '适用于展示产品信息' },
          { id: 3, name: '活动页面', description: '适用于展示活动、促销信息' }
        ]
        localStorage.setItem('contentTemplates', JSON.stringify(templates.value))
      }
    }, 300)
  } catch (error) {
    console.error('获取模板列表失败', error)
  }
}

// 筛选内容列表
const filteredContents = computed(() => {
  let result = [...contents.value]
  
  // 搜索筛选
  if (searchQuery.value) {
    result = result.filter(item => 
      item.title.toLowerCase().includes(searchQuery.value.toLowerCase())
    )
  }
  
  // 状态筛选
  if (statusFilter.value) {
    result = result.filter(item => item.status === statusFilter.value)
  }
  
  // 模板筛选
  if (templateFilter.value) {
    result = result.filter(item => item.template_id === Number(templateFilter.value))
  }
  
  return result
})

// 获取状态类型
const getStatusType = (status: string) => {
  const types: Record<string, string> = {
    'published': 'success',
    'draft': 'info',
    'disabled': 'danger'
  }
  return types[status] || 'info'
}

// 获取状态文本
const getStatusText = (status: string) => {
  const texts: Record<string, string> = {
    'published': '已发布',
    'draft': '草稿',
    'disabled': '弃用'
  }
  return texts[status] || status
}

// 添加内容
const addContent = () => {
  router.push('/admin/content/edit')
}

// 编辑内容
const editContent = (content: ContentItem) => {
  router.push(`/admin/content/edit/${content.id}`)
}

// 预览内容
const previewContent = (content: ContentItem) => {
  // 实际项目中应该打开预览页面
  // 这里我们将内容存储到localStorage，然后打开预览页面
  localStorage.setItem('previewContent', JSON.stringify(content))
  window.open(`/preview/${content.path}`, '_blank')
}

// 删除内容
const deleteContent = (content: ContentItem) => {
  ElMessageBox.confirm(
    `确定要删除"${content.title}"吗？此操作不可恢复。`,
    '删除确认',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(() => {
    // 从列表中删除内容
    contents.value = contents.value.filter(item => item.id !== content.id)
    // 保存到localStorage
    localStorage.setItem('contentItems', JSON.stringify(contents.value))
    ElMessage.success('删除成功')
  }).catch(() => {})
}

// 处理搜索
const handleSearch = () => {
  currentPage.value = 1
}

// 处理筛选
const handleFilter = () => {
  currentPage.value = 1
}

// 处理页码变化
const handlePageChange = (page: number) => {
  currentPage.value = page
}

onMounted(() => {
  fetchTemplates()
  fetchContents()
})
</script>

<style scoped>
.content-list {
  padding: 24px;
  background: #fff;
  min-height: 100%;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.filter-bar {
  display: flex;
  margin-bottom: 20px;
  gap: 15px;
}

.search-input {
  width: 300px;
}

.template-info {
  display: flex;
  align-items: center;
  gap: 5px;
}

.content-title-link {
  color: #409eff;
  cursor: pointer;
}

.content-title-link:hover {
  text-decoration: underline;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: center;
}
</style> 